package com.btex.app.adapter;

import android.content.Context;
import android.content.Intent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
import android.widget.Toast;

import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;
import com.lidroid.xutils.util.PreferencesCookieStore;
import com.btex.app.Config;
import com.btex.app.R;
import com.btex.app.entity.EntrustInfo;
import com.btex.app.tools.LogUtil;

import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by wcx on 16/3/20.
 */
public class EntrustAdapter extends BaseAdapter{
    private Context cxt;
    private List<EntrustInfo> data = new ArrayList<>();
    private String TAG = "EntrustAdapter";
    private PreferencesCookieStore cookieStore;

    public EntrustAdapter(Context cxt,PreferencesCookieStore cookieStore) {
        this.cxt = cxt;
        this.cookieStore =cookieStore;
    }

    @Override
    public int getCount() {
        return data==null?0:data.size();
    }

    public void addData(boolean clear, List<EntrustInfo> entrustInfos){
        if(clear){
            if(entrustInfos!=null)
                LogUtil.i(TAG,"size:"+entrustInfos.size()+" infos:"+entrustInfos.toString());
            data.clear();
            LogUtil.i(TAG, "刷新数据");

        }
        if(entrustInfos!=null)
            data.addAll(entrustInfos);
        notifyDataSetChanged();
    }

    @Override
    public Object getItem(int position) {
        return (data==null||data.size()==0)?null : (data.size()>=position?data.get(position):null);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(final int position, View convertView, ViewGroup parent) {
        ViewHolder holder;
        if (convertView == null) {
            convertView = LayoutInflater.from(cxt).inflate(
                    R.layout.item_entrust_record, null);
            holder = new ViewHolder();
            holder.tvCtime = (TextView) convertView.findViewById(R.id.tv_ctime);
            holder.tvRestNum = (TextView) convertView.findViewById(R.id.tv_rest_num);
            holder.tvState = (TextView) convertView.findViewById(R.id.tv_state);
            holder.tvStockEntrustPrice = (TextView) convertView.findViewById(R.id.tv_stock_entrust_price);
            holder.tvBuySell = (TextView) convertView.findViewById(R.id.tv_buy_sell);
            holder.tvStockEntrustNum = (TextView) convertView.findViewById(R.id.tv_stock_entrust_num);
            convertView.setTag(holder);
        } else {
            holder = (ViewHolder) convertView.getTag();
        }
        final EntrustInfo entrustInfo = (EntrustInfo) getItem(position);
        if(entrustInfo!=null) {

            if("0".equals(entrustInfo.getOrder_status())){    //0:未成交，-1:已取消, 1：已完成
                holder.tvState.setText(cxt.getString(R.string.cancel));
                holder.tvState.setBackgroundResource(R.drawable.selector_blue);
                holder.tvState.setTextColor(cxt.getResources().getColor(R.color.white));
            }else if("1".equals(entrustInfo.getOrder_status())){
                holder.tvState.setText(cxt.getString(R.string.is_traded));
                holder.tvState.setBackgroundResource(R.color.white);
                holder.tvState.setTextColor(cxt.getResources().getColor(R.color.tv_red));
            }else {
                holder.tvState.setText(cxt.getString(R.string.cancelled));
                holder.tvState.setBackgroundResource(R.color.white);
                holder.tvState.setTextColor(cxt.getResources().getColor(R.color.tv_red));
            }
            if("buy".equals(entrustInfo.getOrder_type())){
                holder.tvBuySell.setText(cxt.getString(R.string.buy));
                holder.tvBuySell.setTextColor(cxt.getResources().getColor(R.color.tv_red));
                if("0".equals(entrustInfo.getOrder_status())){    //0:未成交，-1:已取消, 1：已完成
                    holder.tvState.setText(cxt.getString(R.string.cancel));
                    holder.tvState.setBackgroundResource(R.drawable.selector_btn_app_color);
                    holder.tvState.setTextColor(cxt.getResources().getColor(R.color.white));
                }
            }else{
                holder.tvBuySell.setText(cxt.getString(R.string.sell));
                holder.tvBuySell.setTextColor(cxt.getResources().getColor(R.color.tv_green));
                if("0".equals(entrustInfo.getOrder_status())){    //0:未成交，-1:已取消, 1：已完成
                    holder.tvState.setText(cxt.getString(R.string.cancel));
                    holder.tvState.setBackgroundResource(R.drawable.selector_blue);
                    holder.tvState.setTextColor(cxt.getResources().getColor(R.color.white));
                }

            }
            holder.tvCtime.setText(entrustInfo.getCtime());
            holder.tvRestNum.setText(entrustInfo.getRest_num());
            holder.tvStockEntrustPrice.setText(entrustInfo.getPrice());
            holder.tvStockEntrustNum.setText(entrustInfo.getNum());

            holder.tvState.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if("0".equals(entrustInfo.getOrder_status()))
                        toCancel(position);
                }


            });


        }

        return convertView;
    }
    private void toCancel(final int position) {
        RequestParams params = new RequestParams();
        params.addBodyParameter("order_id",data.get(position).getOrder_id());
        new HttpUtils().configCookieStore(cookieStore).send(HttpRequest.HttpMethod.POST, Config.URL_CANCEL_ORDER, params, new RequestCallBack<String>() {
            @Override
            public void onSuccess(ResponseInfo<String> responseInfo) {
                String result = responseInfo.result.toString();
                LogUtil.i(TAG,result);
                try {
                    JSONObject json = new JSONObject(result);
                    if("1".equals(json.getString(Config.KEY_CODE))){
                        Toast.makeText(cxt,cxt.getString(R.string.succeess),Toast.LENGTH_SHORT).show();
                        data.get(position).setOrder_status("-1");
                        notifyDataSetChanged();

                        Intent i = new Intent();
                        i.setAction("tradeactivity_data_changed");
                        cxt.sendBroadcast(i);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(HttpException error, String msg) {

            }
        });
    }


    private static class ViewHolder{
        private TextView tvCtime;
        private TextView tvRestNum;
        private TextView tvState;
        private TextView tvStockEntrustPrice;
        private TextView tvBuySell;
        private TextView tvStockEntrustNum;
    }
}
